import React, {useCallback, useEffect, useState} from "react";
import {Button, Card, Table,Space,Image,Pagination,Modal,Form, Input, Upload } from 'antd';
import { PlusOutlined,FormOutlined,DeleteOutlined } from '@ant-design/icons';
import {
    addTrademarkItemAsync,
    deleteTrademarkItemAsync, editTrademarkItemAsync,
    getTrademarkListAsync,
    useSelectTrademark
} from "@/store/slice/trademark";
import type {UploadProps } from 'antd/es/upload/interface';
import {useAppDispatch} from "@/hooks";
import './index.less'


function Trademark(){
    const dispatch = useAppDispatch()
    const [pageNum,setPageNum] = useState<number>(1)
    const [pageSize,setPageSize] = useState<number>(5)
    //模态框是否显示
    const [isModalOpen, setIsModalOpen] = useState(false);
    //存放当前表单数据
    const [logoItem,setLogoItem] = useState<any>({
        logoUrl:'',
        tmName:''
    })
    //初始化或更新时发请求获取分页数据
    useEffect(()=>{
        dispatch(getTrademarkListAsync(pageNum,pageSize))
    },[pageNum,pageSize])
    //从redux中获取数据
    const {trademarkList:data,total} = useSelectTrademark()
    //页码数据发生变化时调用
    const onChange = (page:any, pageSize:number)=>{
        setPageNum(page)
        setPageSize(pageSize)
    }
    //form表单提交
    const [form] = Form.useForm();
    const onFinish =async (values: any) => {
        setIsModalOpen(false)
        setLogoItem({...logoItem,tmName:values.tmName})
        if(logoItem.id){
            await dispatch(editTrademarkItemAsync(logoItem))
            setFileList([{
                uid: '-1',
                name: '上传图片',
                status: 'done',
                url: '',
            }])
        }else {
            await dispatch(addTrademarkItemAsync(logoItem))
            setFileList([{
                uid: '-1',
                name: '上传图片',
                status: 'done',
                url: '',
            }])
        }
        await dispatch(getTrademarkListAsync(pageNum,pageSize))
        form.resetFields()
    };
    const [fileList, setFileList] = useState<any[]>([
        {
            uid: '-1',
            name: '上传图片',
            status: 'done',
            url: '',
        },
    ]);

    const onImgChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
        setFileList(newFileList);
        console.log(newFileList)
        setLogoItem({...logoItem,logoUrl:newFileList[0]?.response?.data})
    };

    return(
        <>
            <Card>
                <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={()=>{
                        setIsModalOpen(true)
                    }}
                >添加</Button>
                <Table
                    rowKey='id'
                    columns={[
                        {
                            title:"序号",
                            width:70,
                            align:"center",// 居中
                            dataIndex:"id",
                        },
                        {
                            title: '品牌名称',
                            dataIndex: 'tmName',
                            align:"center",// 居中
                        },
                        {
                            title: '品牌logo',
                            align:"center",// 居中
                            render(value){
                                return (
                                    <Image
                                        height={100}
                                        width={180}
                                        src={value.logoUrl}
                                        fallback=""
                                    />
                                )
                            }
                        },
                        {
                            title: '操作',
                            align:"center",// 居中
                            render(value){
                                return(
                                    <Space>
                                        <Button icon={<FormOutlined />} onClick={()=>{
                                            setIsModalOpen(true)
                                            setLogoItem(()=>{
                                                return value
                                            })
                                            form.setFieldsValue(value)
                                            setFileList([{...fileList[0],url:value.logoUrl}])
                                        }}>修改</Button>
                                        <Button
                                            type="primary"
                                            icon={<DeleteOutlined />}
                                            danger
                                            onClick={()=>{
                                                dispatch(deleteTrademarkItemAsync(value.id))
                                                dispatch(getTrademarkListAsync(pageNum,pageSize))
                                            }}
                                        >删除</Button>
                                    </Space>
                                )
                            }
                        },
                    ]}
                    dataSource={data}
                    pagination={false}
                    style={{margin:'20px 0'}}/>
                <Pagination
                    pageSizeOptions={[3,5,7,9]}
                    showSizeChanger
                    onChange={onChange}
                    defaultCurrent={pageNum}
                    total={total}
                />
            </Card>
            <Modal title={logoItem.id? '修改品牌':'添加品牌'} footer={null} visible={isModalOpen} onCancel={()=>{
                setIsModalOpen(false)
                form.resetFields()
            }}>
                <Form form={form} name="control-hooks" onFinish={onFinish}>
                    <Form.Item name="tmName" label="品牌名称" rules={[{ required: true }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label="品牌logo" valuePropName="fileList" rules={[{ required: true }]}>
                        <Upload
                            maxCount={1}
                            action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
                            listType="picture-card"
                            fileList={fileList}
                            onChange={onImgChange}
                        >
                            <div>
                                <PlusOutlined />
                                <div style={{ marginTop: 8 }}>Upload</div>
                            </div>
                        </Upload>
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 16, span: 16 }}>
                        <Space>
                            <Button onClick={()=>{
                                setIsModalOpen(false)
                                form.resetFields()
                            }}>
                                取消
                            </Button>
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    )
}

export default Trademark
